from django.shortcuts import render, render_to_response
from django.http import HttpResponse, FileResponse
import os
from webdav.models import Entry
from config import Config
from lib.stream import stream_media
import base64


def webdav(request, *args):
    if 'Authorization' not in request.headers:
        response = render_to_response('401.html')
        response.status_code = 401
        response['WWW-Authenticate'] = 'Basic realm="Webdav"'
        return response
    else:
        if request.headers['Authorization'] != Config.cru_info['webdav_auth']:
            response = render_to_response('401.html')
            response.status_code = 401
            response['WWW-Authenticate'] = 'Basic realm="Webdav"'
            return response
    local_path = os.path.join(Config.TEMPLATE, request.path.strip('/'))
    if not os.path.isdir(local_path):
        if local_path.endswith('.mp4') or local_path.endswith('.MP4'):
            return stream_media(request, local_path)
        sending = open(local_path, mode='rb')
        return FileResponse(sending)

    host = request.get_host()

    entry_list = list()
    for path in sorted(os.listdir(local_path)):
        full_path = os.path.join(local_path, path)
        file_size = os.path.getsize(full_path)
        new_entry = Entry(path, file_size, os.path.getmtime(full_path), os.path.isdir(full_path))
        entry_list.append(new_entry)
    context = {
        "now_path": request.path,
        "entry_list": entry_list,
        "host": host,
        "django_version": Config.DJANGO_VER,
    }
    return render(request, 'webdav/webdav.html', context)

def src(request, *args):
    request_path = request.path.strip('/')
    sending = open(os.path.join(Config.TEMPLATE, request_path), mode='rb')
    return FileResponse(sending)